#!/usr/bin/bash
#
# Copyright (C) 2024, 2025, Cyrus Li (e21920076@126.com). All rights reserved.
#

#
# Create ssh config file for a couple of remote hosts
#

FILE=$(readlink -f $BASH_SOURCE)
NAME=$(basename $FILE)
CDIR=$(dirname $FILE)
TMPDIR=${TMPDIR:-"/tmp"}

function cleanup
{
    rm -f $TMPDIR/$NAME.*.$$
    exit $1
}

f_config=$TMPDIR/$NAME.config.$$
if [[ -f ~/.ssh/config.default ]]; then
    cat ~/.ssh/config.default > $f_config
else
    cat > $f_config << EOF
###########################################################
# basic setup                                             #
###########################################################
# share connection without user/password
ControlMaster auto
ControlPath /var/tmp/.ssh_mux_%h_%p_%r

# long connection, default is 4h
ControlPersist 720h

# default ssh options
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
EOF
fi

cat >> $f_config << EOF
#
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
# !!! $(date) !!!
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#
EOF

$CDIR/ssh-config-block >> $f_config

printf "Are you sure to create ~/.ssh/config? [Yes/No]: "
typeset -l flag
read flag
if [[ $flag == "yes" ]]; then
    cp $f_config ~/.ssh/config
    cat ~/.ssh/config
else
    cat -n $f_config | sed 's/^/DEBUG> /g'
fi

cleanup 0
